import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { formatMessage, FormattedMessage } from "umi/locale";
import moment from "moment";
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Tree,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table
} from "antd";
import styles from "@/pages/List/TableList.less";

const FormItem = Form.Item;
const { Option } = Select;

const statusMap = ['success', 'default'];
const status = ["正常", "停用"];

/**
 * 新建表单
 */
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleCreate, handleModalVisible,permTreeData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleCreate(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="新建角色"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色名称">
        {form.getFieldDecorator("roleName", {
          rules: [{ required: true, message: "请输入角色名称",min: 2, max: 10 }]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色描述">
        {form.getFieldDecorator("roleDesc", {
          rules: [
            { required: true, message: "请输入角色描述", min: 2, max: 50 }
          ]
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="拥有权限">
        {form.getFieldDecorator("perms", {
          rules: [
            { required: true, message: "请选择所拥有的权限"}
          ]
        })(
          <Input id="perms" type="hidden" />
        )}
        <Tree 
            checkable
            defaultExpandAll
            treeData={permTreeData}
            onCheck={(checkedKeys)=>{
              //设置选择项
              form.setFieldsValue({perms:checkedKeys});
            }}
          />
      </FormItem>
      
    </Modal>
  );
});

/**
 * 修改表单
 */
const UpdateForm = Form.create()(props => {
  const { updateModalVisible, form,values, handleUpdate,handleCheck, handleUpdateModalVisible,permTreeData,checkedPerms } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      //设置编辑ID
      fieldsValue.id = values.id;
      handleUpdate(fieldsValue);
    });
  };

  return (
    <Modal
      destroyOnClose
      style={{ top: 64 }}
      width={600}
      title="编辑角色"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => handleUpdateModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色名称">
        {form.getFieldDecorator("roleName", {
          rules: [
            { required: true, message: "请输入角色名称", min: 2, max: 10 }
          ],
          initialValue: values.roleName
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="角色描述">
        {form.getFieldDecorator("roleDesc", {
          rules: [
            { required: true, message: "请输入角色描述", min: 2, max: 50 }
          ],
          initialValue: values.roleDesc
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label="拥有权限">
        {form.getFieldDecorator("perms", {
          rules: [
            { required: true, message: "请选择所拥有的权限"}
          ],
          initialValue: checkedPerms
        })(
          <Input id="perms" type="hidden" />
        )}
        <Tree 
            checkable
            defaultExpandAll
            checkedKeys={checkedPerms}
            treeData={permTreeData}
            onCheck={(keys)=>{
              //设置tree选中项
              handleCheck(keys);
              //设置选择项
              form.setFieldsValue({perms:keys});
            }}
          />
      </FormItem>
    </Modal>
  );
});

@connect(({ role,permission, loading }) => ({
  roleData: role.data,
  permTreeData: permission.permTreeData,
  listLoading: loading.models.role
}))
class RoleView extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    formValues: {},
    initFormValues: {},
    checkedPerms:[]
  };

  columns = [
    {
      title: "角色名称",
      dataIndex: "roleName"
    },
    {
      title: "角色描述",
      dataIndex: "roleDesc"
    },
    {
      title: "员工数量",
      dataIndex: "staffCount"
    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: "操作",
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDeleteModalVisible(record)}>删除</a>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "role/list"
    });
    // 加载权限数据
    dispatch({
      type: "permission/listAll"
    });
  }

  handleTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}-${sorter.order}`;
    }

    dispatch({
      type: "role/list",
      payload: params
    });
  };

  handleQuery = fieldsValue => {
    const { dispatch } = this.props;
    dispatch({
      type: "role/list",
      payload: fieldsValue
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
  };

  handleCreate = formValues => {
    const { dispatch } = this.props;
    
    dispatch({
      type: "role/create",
      payload: formValues
    });

    message.success("添加成功");
    this.handleModalVisible();
  };

  handleUpdateModalVisible = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      updateModalVisible: !!flag,
      initFormValues: record || {}
    });

    if(record){
      //获取已选择的权限
      dispatch({
        type: 'role/listPerms',
        payload: {
          roleId: record.id
        },
        callback:(response)=>{
          //设置权限选中值
          this.setState({
            checkedPerms:response.data
          });
        }
      });
    }
    
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/update',
      payload: {
        perms: fields.perms,
        roleDesc: fields.roleDesc,
        roleName: fields.roleName,
        id: fields.id,
      },
    });

    message.success('编辑成功');
    this.handleUpdateModalVisible();
  };

  handleCheck = checkedKeys => {
    this.setState({
      checkedPerms:checkedKeys
    });
  }

  handleDeleteModalVisible = (record) => {
    Modal.confirm({
      title: '删除角色',
      content: '确定删除该角色吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.deleteItem(record.id),
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/delete',
      payload: { id },
    });
  };

  render() {
    const { roleData,permTreeData, listLoading } = this.props;
    const {
      modalVisible,
      updateModalVisible,
      initFormValues,
      checkedPerms
    } = this.state;

    const createMethods = {
      handleCreate: this.handleCreate,
      handleModalVisible: this.handleModalVisible
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      handleCheck: this.handleCheck
    };
    const queryMethods = {
      handleQuery:this.handleQuery,
    }

    return (
      <div>
        <div className={styles.tableList}>
          
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>新建</Button>
          </div>
          <Table
            rowKey="id"
            loading={listLoading}
            dataSource={roleData.list}
            pagination={roleData.pagination}
            columns={this.columns}
            onChange={this.handleTableChange}
            size="middle"
          />
        </div>
        <CreateForm {...createMethods} modalVisible={modalVisible} permTreeData={permTreeData} />
        <UpdateForm {...updateMethods} updateModalVisible={updateModalVisible} values={initFormValues} permTreeData={permTreeData} checkedPerms={checkedPerms}/>
      </div>
    );
  }
}

export default RoleView;
